package dao;


import modle.User;
import util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 1、用于对用户账号密码数据库的各种操作
 * 2、只适用于MySQL数据库
 * 
 * @author Lzx
 *
 */

public class UserDaoJdbcImpl implements UserDAO {

	@SuppressWarnings("resource")
	@Override
	public boolean writeUser(User user) {
		Connection conn = null;
		PreparedStatement pstat = null;
		String sq = "select * from user where account like " + user.getAccount();
		//表中有account和password这列
		String sql = "insert into User(account,password) values(?,?)";
		int result = -1;
		
		try {
			conn = JdbcUtil.getConnection();
			pstat = conn.prepareStatement(sq);
			ResultSet rs = pstat.executeQuery();
			if( rs.next() ) {
				result = 0;
			}else {
				pstat = conn.prepareStatement(sql);
				pstat.setString(1,user.getAccount());
				pstat.setString(2,user.getPassword());
				result = pstat.executeUpdate();
			}
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.realeaseAll(null,pstat, conn);
		}
		return result>0?true:false;
		
	}

	@Override
	public User readUser(String account) {
		Connection conn = null;
		PreparedStatement pstat = null;
		ResultSet rs = null;
		//表中有account和password这列
		String sql = "select * from user where account like ?";
		User user = null;
		
		try {
			conn = JdbcUtil.getConnection();
			pstat = conn.prepareStatement(sql);
			pstat.setString(1, account);
			rs = pstat.executeQuery();
			while(rs.next()){
				String ac = rs.getString("account");
				String ps = rs.getString("password");
				System.out.println("ac: " + ac + " ps: " + ps);
				user = new User(ac, ps); 
			}
		}catch (SQLException sqle) {
			sqle.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JdbcUtil.realeaseAll(rs,pstat, conn);
		}
		return user;
	}

}
